package com.ruicar.afs.cloud.account.common.component;

import com.ruicar.afs.cloud.account.common.send.VoucherItemSendService;
import com.ruicar.afs.cloud.common.core.service.ServiceInfo;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author infinity
 * @version 1.0
 * @date 2020/8/11 19:03
 */
@Component
@Slf4j
@AllArgsConstructor
public class VoucherItemPublishComponent implements ApplicationListener<ApplicationReadyEvent> {
    private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
    private final VoucherItemSendService voucherItemSendService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        schedule();
    }

    public void publishVoucherItemPublish(String serviceName) {
        try {
            log.info("凭证辅助帐发送--start");
            voucherItemSendService.voucherItemSend();
            log.info("凭证辅助帐发送--end");
        } catch (Throwable e) {
            log.error("凭证辅助帐发送异常", e);
        }
    }

    private void schedule() {
        //每60s 检测发布处理一次凭证辅助帐发送
        EXECUTOR_SERVICE.scheduleWithFixedDelay(() -> {
            SpringContextHolder.getBean(VoucherItemPublishComponent.class).publishVoucherItemPublish(ServiceInfo.getServiceName() + 9);
        }, 2, 60, TimeUnit.SECONDS);

    }
}
